var prefix = ctx +"module/fireWork"
$(function() {
    load();
});
var form, table;
function load() {
    layui.use(['form', 'table','laydate'], function () {
        form = layui.form;
        table = layui.table;
        var laydate = layui.laydate;
        //日期时间范围
        // laydate.render({
        //     elem: '#timeRange'
        //     ,type: 'date'
        //     ,range: true
        // });

        laydate.render({
            elem: '#begin_date',
            isInitValue: false,
        });
        laydate.render({
            elem: '#end_date',
            isInitValue: false,
        });


        var searchParams = {};
        // searchParams['timeRange']=$('#timeRange').val();
        searchParams['shopId']=$('#shopId').val();
        searchParams['recordType']=$('#recordType').val();
        searchParams['pianquId']=$('#pianquId').val();

        if($('#begin_date').val() !== "" && $('#end_date').val() !== ""){
            searchParams['begin_date'] = $('#begin_date').val() + " 00:00:00";
            searchParams['end_date'] = $('#end_date').val() + " 23:59:59";
        }
        var toolBar = ''
        var cols = []
        var recordType = $('#recordType').val();
        if(recordType == 0){
            toolBar = '#toolbarDemo'
            cols = [
                {field: 'recordNo', title: '作业证编号', align: 'center',},
                {field: 'regCompanyName', title: '申请动火单位', align: 'center', width: 200},
                {field: 'fireAddress', title: '动火地点', align: 'center',},
                {field: 'safeUserName', title: '安全员', align: 'center',},
                {field: 'lastSubmitUserName', title: '最后审核人', align: 'center',},
                // {field: 'lastSubmitUserName', title: '最后审核人', align: 'center',},
                {field: 'fireBeginTime', title: '动火时间', align: 'center',width: 200,
                    templet: function (item) {
                        return item.fireBeginTime + '~' + item.fireEndTime;
                    },
                },
                {field: 'fireType', title: '动火方式', align: 'center',
                    templet: function (item) {
                        if (item.fireType == 0) {
                            return '电焊';
                        }else if (item.fireType == 1) {
                            return '等离子';
                        }else if (item.fireType == 2) {
                            return '气焊(割)';
                        }else if (item.fireType == 3) {
                            return '喷灯';
                        }else if (item.fireType == 4) {
                            return '其他';
                        } else {
                            return '';
                        }
                    },
                },
                {field: 'opLevel', title: '作业级别', align: 'center',
                    templet: function (item) {
                        if (item.opLevel == 1) {
                            return '非生产区域动火';
                        } else if (item.opLevel == 2) {
                            return '生产区域动火';
                        } else {
                            return '';
                        }
                    },
                },
                // {field: 'recordHeaderUser', title: '责任人', align: 'center',},
                {field: 'createTime', title: '申请时间', align: 'center',},
                {
                    field: 'state', title: '状态', align: 'center',
                    templet: function (item) {
                        if (item.state == 0 &&  (item.safeOpState == 0 && item.headerOpState == 0)) {
                            return '<span class="label label-danger">待巡查</span>';
                        } else if (item.state == 0 &&  (item.safeOpState == 1 || item.headerOpState == 1)) {
                            return '<span class="label label-warning">巡查中</span>';
                        } else if (item.state == 1){
                            return '<span class="label label-success ">已处理</span>';
                        } else if (item.state == 2){
                            return '<span class="label label-success ">已通过</span>';
                        } else if (item.state == 3){
                            return '<span class="label label-success ">已验收</span>';
                        } else if (item.state == 4){
                            return '<span class="label label-success ">已驳回</span>';
                        }  else {
                            return '<span class="label label-success "></span>';
                        }
                    },
                },
                { title: '操作', width: 200, templet: '#currentTableBar', fixed: "right", align: "center"}
            ];
        } else if(recordType == 1){
            cols = [
                {field: 'recordNo', title: '作业证编号', align: 'center',},
                {field: 'regCompanyName', title: '申请作业单位', align: 'center',},
                {field: 'fireAddress', title: '作业地点', align: 'center',},
                {field: 'workHeight', title: '作业高/深度（米）', align: 'center',},
                // {field: 'recordHeaderUser', title: '作业责任人', align: 'center',},
                {field: 'safeUserName', title: '作业安全员', align: 'center',},
                {field: 'recordHeaderUser', title: '作业时间', align: 'center',
                    templet: function (item) {
                        return item.fireBeginTime + '~' + item.fireEndTime;
                    },
                },
                {field: 'opLevel', title: '作业等级', align: 'center',
                    templet: function (item) {
                        if (item.opLevel == 1) {
                            return '一级';
                        }else {
                            return '特级';
                        }
                    },
                },
                // {field: 'workType', title: '工种', align: 'center',},
                // {field: 'recordHeaderUser', title: '责任人', align: 'center',},
                {field: 'createTime', title: '申请时间', align: 'center',},
                {
                    field: 'state', title: '状态', align: 'center',
                    templet: function (item) {
                        if (item.state == 0 &&  (item.safeOpState == 0 && item.headerOpState == 0)) {
                            return '<span class="label label-danger">待巡查</span>';
                        } else if (item.state == 0 &&  (item.safeOpState == 1 || item.headerOpState == 1)) {
                            return '<span class="label label-warning">巡查中</span>';
                        } else if (item.state == 1){
                            return '<span class="label label-success ">已处理</span>';
                        } else if (item.state == 2){
                            return '<span class="label label-success ">已通过</span>';
                        } else if (item.state == 3){
                            return '<span class="label label-success ">已验收</span>';
                        } else if (item.state == 4){
                            return '<span class="label label-success ">已驳回</span>';
                        }  else {
                            return '<span class="label label-success "></span>';
                        }
                    },
                },
                { title: '操作', width: 200, templet: '#currentTableBar', fixed: "right", align: "center"}
            ];
        } else if(recordType == 2){
            toolBar = '#toolbarHigh'
            cols = [
                {field: 'recordNo', title: '作业证编号', align: 'center',},
                {field: 'regUserName', title: '申请人', align: 'center',},
                {field: 'regCompanyName', title: '申请作业单位', align: 'center',},
                {field: 'fireAddress', title: '作业地点', align: 'center',},
                {field: 'safeUserName', title: '安全督导员', align: 'center',},
                // {field: 'safeUserName', title: '生产经理', align: 'center',},
                {field: 'recordHeaderUser', title: '作业时间', align: 'center',
                    templet: function (item) {
                        return item.fireBeginTime + '~' + item.fireEndTime;
                    },
                },
                {field: 'workContent', title: '作业内容', align: 'center',},
                {field: 'workHeight', title: '作业高度', align: 'center',},
                {field: 'createTime', title: '申请时间', align: 'center',},
                {
                    field: 'state', title: '状态', align: 'center',
                    templet: function (item) {
                        if (item.state == 0 &&  (item.safeOpState == 0 && item.headerOpState == 0)) {
                            return '<span class="label label-danger">待巡查</span>';
                        } else if (item.state == 0 &&  (item.safeOpState == 1 || item.headerOpState == 1)) {
                            return '<span class="label label-warning">巡查中</span>';
                        } else if (item.state == 1){
                            return '<span class="label label-success ">已处理</span>';
                        } else if (item.state == 2){
                            return '<span class="label label-success ">已通过</span>';
                        } else if (item.state == 3){
                            return '<span class="label label-success ">已验收</span>';
                        } else if (item.state == 4){
                            return '<span class="label label-success ">已驳回</span>';
                        }  else {
                            return '<span class="label label-success "></span>';
                        }
                    },
                },
                { title: '操作', width: 200, templet: '#currentTableBar', fixed: "right", align: "center"}
            ];
        }
        //初始化table
        table.render({
            elem: '#exampleTable',//承载数据的table Id
            url: prefix + "/list",//请求数据连接
            // toolbar: '#toolbarDemo',
            toolbar: toolBar,
            cellMinWidth: 80,//全局定义所有常规单元格的最小宽度（默认：60）
            even: true,//是否开启隔行变色
            loading:true,//是否显示加载条
            where :{
                searchParams:searchParams
            },
            //page: true,//是否分页
            page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                layout: [ 'prev', 'page', 'next', 'skip', 'count','limit'] //自定义分页布局
            },
            cols: [cols],
            id: 'currentTableId',//表格Id
            done: function(res, curr, count){
                // $('.layui-table-fixed-r').removeClass('layui-hide');
                // $(".grid-column-qrcode").each(function() {
                //     $(this).click(function() {
                //         previewImg($(this));
                //     })
                // });
            } //解决最右侧列不能固定的问题
        });
        /**
         * 操作栏tool  监听事件
         */
        table.on('tool(currentTableFilter)', function (obj) {
            if (obj.event === 'edit') {  // 监听添加操作
                edit(obj.data.id);
            } else if (obj.event === 'delete') {  // 监听删除操作
                remove(obj.data.id);
            } else if (obj.event === 'generateTicket') {  // 监听删除操作
                generateTicket(obj);
            } else if (obj.event === 'detail') {  // 详情
                detail(obj.data.id);
            }
        });
        // 监听搜索操作
        form.on('submit(data-search-btn)', function (data) {
            //执行搜索重载
            reLoad();
            return false;
        });

        /**
         * 工具栏  监听事件
         */
        table.on('toolbar(currentTableFilter)', function (obj) {
            if (obj.event === 'add') {  // 监听添加操作
                add();
            } else if(obj.event === 'export'){
                exportRecord();
            } else if(obj.event === 'exportWorkCount'){
                exportWorkCount();
            } else if(obj.event === 'exportWorkCountInfo'){
                exportWorkCountInfo();
            }
        });
    });
}
function townIdChange(townId) {
    $.ajax({
        type: "POST",
        url: ctx +"module/company/getList",
        data: {
            townId: townId
        },
        success: function (data) {
            if (data.code == 0) {
                var shopList = data.data;
                $("#shopId").html("");
                if (shopList.length > 0) {
                    $("#shopId").append("<option value=\"\" selected=\"selected\">所属企业</option>");
                    for (var index in shopList) {
                        var str = "<option value=\"" + shopList[index].id + "\" >" + shopList[index].shopName + "</option>";
                        $("#shopId").append(str);
                    }
                } else {
                    var str = "<option value=\"\" selected=\"selected\">----无----</option>";
                    $("#shopId").append(str);
                }
                form.render("select");
            }
        }
    });
}
function reLoad() {
    var searchParams = {};
    // searchParams['timeRange']=$('#timeRange').val();
    searchParams['shopId']=$('#shopId').val();
    searchParams['recordType']=$('#recordType').val();
    searchParams['pianquId']=$('#pianquId').val();
    if($('#begin_date').val() !== "" && $('#end_date').val() !== ""){
        searchParams['begin_date'] = $('#begin_date').val() + " 00:00:00";
        searchParams['end_date'] = $('#end_date').val() + " 23:59:59";
    }

    layui.use(['table'], function() {
        var table = layui.table;//载入table模块
        var  page = $(".layui-laypage-skip").find("input").val() //当前页码值
        console.log('page',page)
        table.reload('currentTableId', {
            page: {curr: page }
            , where: {
                searchParams: searchParams
            }
        }, 'data');
    });
}


function exportRecord() {
    var shopId = $("#shopId").val();
    var timeRange = $('#timeRange').val();
    var recordType =$('#recordType').val();
    var pianquId =$('#pianquId').val();
    // var timeRanges =  timeRange.split("-");
    // console.log('timeRanges',timeRanges)

    var begin_date = $("#begin_date").val();
    var end_date = $("#end_date").val();

    window.location.href = ctx + 'module/fireWork/exportExcel?shopId='
        + shopId + '&begin_date='+begin_date+'&end_date=' + end_date + '&recordType=' + recordType+ '&pianquId=' + pianquId;
}

function exportWorkCount() {
    var shopId = $("#shopId").val();
    var timeRange = $('#timeRange').val();
    var recordType =$('#recordType').val();
    var pianquId =$('#pianquId').val();
    // var timeRanges =  timeRange.split("-");
    // console.log('timeRanges',timeRanges)

    var begin_date = $("#begin_date").val();
    var end_date = $("#end_date").val();
    if (begin_date && !end_date){
        layer.msg('请选择结束时间！');
        return;
    }
    if (!begin_date && end_date){
        layer.msg('请选择开始时间！');
        return;
    }
    window.location.href = ctx + 'module/fireWork/exportWorkCount?shopId='
        + shopId + '&begin_date='+begin_date+'&end_date=' + end_date + '&recordType=' + recordType+ '&pianquId=' + pianquId;
}
function exportWorkCountInfo() {
    var shopId = $("#shopId").val();
    var timeRange = $('#timeRange').val();
    var recordType =$('#recordType').val();
    var pianquId =$('#pianquId').val();
    // var timeRanges =  timeRange.split("-");
    // console.log('timeRanges',timeRanges)

    var begin_date = $("#begin_date").val();
    var end_date = $("#end_date").val();
    if (begin_date && !end_date){
        layer.msg('请选择结束时间！');
        return;
    }
    if (!begin_date && end_date){
        layer.msg('请选择开始时间！');
        return;
    }
    window.location.href = ctx + 'module/fireWork/exportWorkCountInfo?shopId='
        + shopId + '&begin_date='+begin_date+'&end_date=' + end_date + '&recordType=' + recordType+ '&pianquId=' + pianquId;
}


function previewImg(obj) {
    var img = new Image();
    img.src = $(obj).attr("src");
    var imgHtml = "<img src='" + img.src + "' width='100%' height='100%' style='object-fit:contain' />";
    //弹出层
    layer.open({
        type: 1,
        // shade: true,
        shadeClose : true, // 点击遮罩关闭层
        area:['80%','80%'],
        title: false, //不显示标题
        content: imgHtml, //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
        cancel: function () {

        }
    });
}


function add() {
    var index = layer.open({
        type : 2,
        title : '增加',
        maxmin : true,
        shadeClose : false, // 点击遮罩关闭层
        area : [ '800px', '420px' ],
        content : prefix + '/add' // iframe的url
    });
    layer.full(index);
}


function edit(id) {
    var index = layer.open({
        type : 2,
        title : '回复',
        maxmin : true,
        shadeClose : false, // 点击遮罩关闭层
        area : [ '800px', '520px' ],
        content : prefix + '/edit/' + id // iframe的url
    });

    layer.full(index);
}
function detail(id) {
    var index = layer.open({
        type : 2,
        title : '详情',
        maxmin : true,
        shadeClose : false, // 点击遮罩关闭层
        area : [ '650px', '550px' ],
        content : prefix + '/detail/' + id // iframe的url
    });

    // layer.full(index);
}
function remove(id) {
    layer.confirm('确定要删除选中的记录？', {
        btn : [ '确定', '取消' ]
    }, function() {
        $.ajax({
            url : prefix+"/remove",
            type : "post",
            data : {
                'id' : id
            },
            success : function(r) {
                if (r.code==0) {
                    layer.msg(r.msg);
                    reLoad();
                }else{
                    layer.msg(r.msg);
                }
            }
        });
    })
}



function generateTicket(obj) {
     if (obj.data.state === 2 || obj.data.state === 3){
        layer.confirm('确定要生成安全作业票吗？', {
            btn : [ '确定', '取消' ]
        }, function() {
            window.location.href = ctx +"module/fireSafetyTicket/downloadTicket/" + obj.data.id;
            layer.closeAll();
        })
     }else {
         layer.msg('此状态不能生成安全作业票！');
     }
}
